/**
 * Created by tanbingqin on 2021/1/5.
 */
import React, { Component, PropTypes } from "react";
import { Form, Select, Input, Spin } from "antd";
import { messages, deepFullCopy } from "share/common";
import formService from "containers/setting/form/form.service";
import debounce from "lodash.debounce";
const Option = Select.Option;

class RelationField extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectType: null, //选中的引用对象
      fieldList: [], //引用字段list
      loading: false,
      selectField: null, //选中的引用字段
    };
    this.fieldTypeMap = {
      101: messages("request-2.key516") /*文本*/,
      105: messages("common.date") /*日期*/,
    };
    this.getFieldList = debounce(this.getFieldList, 500);
  }

  componentDidMount() {
    const { value } = this.props;
    this.setValue(this.props.value);
  }

  componentWillReceiveProps(nextProps) {
    if ("value" in nextProps) {
      this.setValue(nextProps.value);
    }
  }

  setValue = (dataSource) => {
    if (dataSource) {
      let tempDataSource = JSON.parse(dataSource);
      let isNeedGetFieldList =
        !this.state.selectType || tempDataSource.relationType !== this.state.selectType.relationType;
      this.setState(
        {
          selectType: {
            linkageFieldOID: tempDataSource.linkageFieldOID,
            relationType: tempDataSource.relationType,
          },
          selectField: {
            fieldCode: tempDataSource.linkageFieldCode,
            dataType: tempDataSource.linkageDataType,
            fieldTypeId: tempDataSource.fieldTypeId,
          },
        },
        () => {
          if (isNeedGetFieldList) {
            this.getFieldList();
          }
        }
      );
    } else {
      this.setState({
        selectType: null,
        selectField: null,
        fieldList: [],
      });
    }
  };

  processRelationList = () => {
    const { widgetList } = this.props;
    let list = [];
    widgetList &&
      widgetList.forEach((widget) => {
        let relationType = widget.dataSource ? JSON.parse(widget.dataSource).relationType : undefined;
        if (widget.messageKey === "relation_obj" && widget.fieldName && relationType) {
          list.push({
            fieldName: widget.fieldName,
            linkageFieldOID: widget.fieldOID,
            relationType,
          });
        }
      });
    return list;
  };

  findRelationName = () => {
    const { relationTypeList } = this.props;
    const { selectType } = this.state;
    let relationName = "";
    let relationType = selectType ? selectType.relationType : undefined;
    let relationItem = relationTypeList.find((item) => item.type === relationType);
    if (relationType && relationItem) {
      relationName = relationItem.name;
    }
    return relationName;
  };

  //选择引用对象
  handleSelectType = (e, opt) => {
    this.setState(
      {
        selectType: opt.props["data-type"],
        selectField: null,
        fieldList: [],
      },
      () => {
        this.dispatchOnChange();
        this.getFieldList();
      }
    );
  };

  getFieldList = () => {
    const { selectType } = this.state;
    let relationType = selectType ? selectType.relationType : undefined;
    if (relationType) {
      this.setState({ loading: true });
      formService
        .getRelationFields(relationType)
        .then((res) => {
          this.setState({ fieldList: res.data || [], loading: false });
        })
        .catch(() => {
          this.setState({ loading: false });
        });
    }
  };

  //选择引用字段
  handleSelectField = (e, opt) => {
    this.setState(
      {
        selectField: opt.props["data-field"],
      },
      this.dispatchOnChange
    );
  };

  dispatchOnChange = () => {
    const { selectType, selectField } = this.state;
    const { onChange } = this.props;
    let result = {};
    if (selectType) {
      result.linkageFieldOID = selectType.linkageFieldOID;
      result.relationType = selectType.relationType;
    }
    if (selectField) {
      result.linkageFieldCode = selectField.fieldCode;
      result.linkageDataType = selectField.dataType;
      result.fieldTypeId = selectField.fieldTypeId;
    }
    onChange && onChange(result);
  };

  render() {
    const { disabled } = this.props;
    const { selectType, loading, fieldList, selectField } = this.state;
    return (
      <div>
        <div className="form-title">{messages("request-2.key517") /*引用对象：*/}</div>
        <Select
          disabled={disabled}
          onSelect={(e, opt) => this.handleSelectType(e, opt)}
          getPopupContainer={(triggerNode) => triggerNode.parentNode}
          defaultActiveFirstOption={false}
          placeholder={messages("common.select") /*请选择*/}
          value={selectType ? selectType.linkageFieldOID || undefined : undefined}
        >
          {this.processRelationList().map((item) => (
            <Option data-type={item} key={item.linkageFieldOID}>
              {item.fieldName}
            </Option>
          ))}
        </Select>
        {selectType && selectType.relationType && (
          <div className="form-title-description" style={{ marginTop: 5 }}>
            {messages("request-2.key518") /*对象类型：*/}
            {this.findRelationName()}
          </div>
        )}
        <Spin spinning={loading}>
          <div className="form-title">{messages("request-2.key519") /*引用字段：*/}</div>
          <Select
            disabled={disabled || !selectType || !selectType.relationType}
            onSelect={(e, opt) => this.handleSelectField(e, opt)}
            getPopupContainer={(triggerNode) => triggerNode.parentNode}
            defaultActiveFirstOption={false}
            placeholder={messages("common.select") /*请选择*/}
            value={
              selectField && selectField.fieldCode ? `${selectField.fieldCode}|${selectField.dataType}` : undefined
            }
          >
            {fieldList.map((item) => (
              <Option data-field={item} key={`${item.fieldCode}|${item.dataType}`}>
                {item.fieldName}
              </Option>
            ))}
          </Select>
        </Spin>
        {selectField && selectField.fieldTypeId && (
          <div className="form-title-description" style={{ marginTop: 5 }}>
            {messages("request-2.key520") /*字段类型：*/}
            {this.fieldTypeMap[selectField.fieldTypeId]}
          </div>
        )}
      </div>
    );
  }

  static propTypes = {
    onChange: PropTypes.func,
    widgetList: PropTypes.array,
    relationTypeList: PropTypes.array,
    disabled: PropTypes.bool,
  };

  static defaultProps = {
    onChange: () => {},
    widgetList: [],
    relationTypeList: [],
    disabled: false,
  };
}

export default RelationField;
